package com.jhy.guavacase.io;

import com.google.common.base.Charsets;
import com.google.common.hash.HashCode;
import com.google.common.hash.Hashing;
import com.google.common.io.*;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.io.File;
import java.io.IOException;

/**
 * @author jhy
 * @ClassName ByteSinkCase.java
 * @Description ByteSink示例
 * @createTime 2022年03月14日 19:59:00
 */
public class ByteSinkCase {

    private final String byteSinkPath = "E:\\java项目\\Guava学习\\guava-case\\guava-case\\src\\main\\resources\\io\\byteSink.txt";
    //1.write就是将字节数组写出
    @Test
    public void testByteSinkWrite() throws IOException {

        File file = new File(byteSinkPath);
        file.deleteOnExit();
        //使用ByteSink写出
        ByteSink byteSink = Files.asByteSink(file, FileWriteMode.APPEND);
        byte[] bytes = {0,1,2,3,4,5,6,7,8,9};
        byteSink.write(bytes);
        Assertions.assertTrue(file.exists());
        //使用ByteSource读入
        ByteSource byteSource = Files.asByteSource(file);
        byte[] read = byteSource.read();
        for (int i = 0; i < read.length; i++) {
            System.out.println(read[i]);
        }
    }

    //2.copyTo() //ByteSource中的方法
    //将ByteSource中的数据复制到ByteSink
    @Test
    public void testByteSourceCopyTo() throws IOException {

        String sourcePath = "E:\\java项目\\Guava学习\\guava-case\\guava-case\\src\\main\\resources\\io\\sourceFile.txt";
        String targetPath = "E:\\java项目\\Guava学习\\guava-case\\guava-case\\src\\main\\resources\\io\\targetFile.txt";

        File sourceFile = new File(sourcePath);
        File targetFile = new File(targetPath);
        targetFile.deleteOnExit();

        ByteSource byteSource = Files.asByteSource(sourceFile);
        ByteSink byteSink = Files.asByteSink(targetFile);
        byteSource.copyTo(byteSink);
        Assertions.assertTrue(targetFile.exists());
        //使用hash判断是否复制内容一致
        HashCode sourceHash = byteSource.hash(Hashing.sha256());
        HashCode targetHash = Files.asByteSource(targetFile).hash(Hashing.sha256());
        Assertions.assertEquals(sourceHash,targetHash);
    }
}
